package com.java.test.system.controller;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.java.test.controller.BaseController;
import com.java.test.system.dto.LoginAccountInfo;
import com.java.test.system.dto.MenuInfo;
import com.java.test.util.HttpErrorCode;
import com.java.test.util.IpUtils;
import com.java.test.util.JsonResult;
import com.java.test.util.JsonUtil;
import com.java.test.util.RedisUtil;
import com.java.test.util.TokenUtil;
import com.java.test.util.VerifyCodeUtils;

@RestController
@RequestMapping("/user")
public class LoginController extends BaseController {

	@Autowired
	private RedisUtil redisUtil;

	@RequestMapping(value = "yzm")
	public void yzm(HttpServletRequest request, HttpServletResponse response) throws IOException {
		
		//List<String> obj = redisUtil.hsetvaluesyyy("NewUserDataBuffer");
		
		
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
		response.setContentType("image/jpeg");
		// 生成随机字串
		String verifyCode = VerifyCodeUtils.generateVerifyCode(4);
		// 存入会话session
		// System.out.println("sessionid1:"+request.getSession().getId());
		HttpSession session = request.getSession(true);
		System.out.println(request.getSession().getId());
		// 删除以前的
		session.removeAttribute("verCode");
		session.removeAttribute("codeTime");
		session.setAttribute("verCode", verifyCode.toLowerCase()); // 生成session
		session.setAttribute("codeTime", LocalDateTime.now());
		// 生成图片
		int w = 100, h = 30;
		OutputStream out = response.getOutputStream();
		String base64Img = VerifyCodeUtils.outputImage(w, h, out, verifyCode);
		System.out.println("================ppppppppppppppppppp============================="+verifyCode.toLowerCase());
//		JSONObject json = new JSONObject();
//		json.put("msg", "token verify fail");
//		json.put("data", base64Img);
//		PrintWriter pw = response.getWriter();
//		pw.write(json.toJSONString());

	}

	@RequestMapping("/login")
	public JsonResult getAllUser(@RequestBody LoginAccountInfo infos, HttpServletRequest request) {

		JsonResult json = new JsonResult(HttpErrorCode.REQUESTSUCCESS.getCode(),
				HttpErrorCode.REQUESTSUCCESS.getContent());
		System.out.println("sessionid2:" + request.getSession().getId());
		HttpSession session = request.getSession();

		String sessionId = request.getSession().getId();

		

		String code = request.getParameter("verCode").toLowerCase();

		System.out.println("scode:" + session.getAttribute("verCode") + "rcode=====" + code);

		if (!code.equals(session.getAttribute("verCode"))) {
			json.setMessage(HttpErrorCode.YZMCODEERROR.getContent());
			json.setCode(HttpErrorCode.YZMCODEERROR.getCode());
			return json;
		}

		LoginAccountInfo info = systemManageService.loginuser(infos.getLoginAccout(), infos.getPassWord());
		if (info == null) {
			json.setMessage(HttpErrorCode.LOGINERROR.getContent());
			json.setCode(HttpErrorCode.LOGINERROR.getCode());
			return json;
		}
		int status = info.getStatus();
		if (status == 2) {
			json.setMessage(HttpErrorCode.LOGINUSERSTATUSERROR.getContent());
			json.setCode(HttpErrorCode.LOGINUSERSTATUSERROR.getCode());
			return json;
		}

		// 用户通过登录 -- 需要下发权限列表 
		List<MenuInfo> list = systemManageService.selectloginuserMenu(info.getRoleId());

		// 写日志
		info.setIp(IpUtils.getIpAddress(request));
		systemManageService.insertlogInfo(info.getLoginAccout(), IpUtils.getIpAddress(request), "用户登陆系统");

		String token = TokenUtil.sign(JsonUtil.ObjString(info));
		// sso Auth
		info.setTokenVerify(token);

		Object obj = redisUtil.hgetvalues("ONLINE_USER", info.getLoginAccout());
//		List<LoginAccountInfo> tlist = new ArrayList<LoginAccountInfo>();
//		if (obj != null) {
//			tlist = JsonUtil.jsonArray2List(obj.toString(), LoginAccountInfo.class);
//			boolean isexits=false;
//			for (LoginAccountInfo b : tlist) {
//				if (b.getIp() != null && !"".equals(b.getIp()) && b.getIp().equals(info.getIp())) {
//					isexits=true;
//				}	
//			}	
//			if(!isexits) {
//				tlist = new ArrayList<LoginAccountInfo>();
//		}		
//			tlist.add(info);
//
//		}else {
//			tlist.add(info);
//		}
//     38960
//		redisUtil.hset("ONLINE_USER", info.getLoginAccout(), JsonUtil.obj2json(tlist));

		redisUtil.hset("ONLINE_USER_SESSION", info.getLoginAccout(), sessionId);

		JSONObject reobj = new JSONObject();
		reobj.put("token", token);
		reobj.put("user", info);
		reobj.put("menu", list);

		json.setData(reobj);
		// 10:36
		return json;
	}

}
